<template>
  <a-card :bordered="false">
    <a-spin :spinning="uploading">
      <div style="display: flex; padding: 14px 0; line-height: 40px">
        <a-checkbox style="font-weight: bold; color: #000" v-model="clearManageLog.ivalue">
          {{$t('管理日志')}}
        </a-checkbox>
        <a-button v-enable-if="'BisSysParameterController:edit'" type="primary" style="margin-left: 20px" @click="parameterChange('clearManageLog')">
          {{ $t('保存')}}
        </a-button>
        <span style="color: orange; line-height: 41px; margin-bottom: 10px">
          {{ $t('（启用后使用系统自动清理功能的管理日志也仅保留设定天数内的日志；且执行磁盘空间清理时会将管理日志一并清除。不启用则均不清除）') }}
        </span>
      </div>

      <a-button v-enable-if="'BisSysParameterController:edit'" type="primary" @click="verifyKeyCard">{{
        $t('磁盘空间清理')
        }}</a-button>
      <div style="color: orange; line-height: 41px; margin-bottom: 10px">
        {{ $t('注意：1.该操作将清空系统历史账目和记录且不可逆;请谨慎操作') }}
      </div>
      <div style="color: orange; line-height: 41px; margin-bottom: 10px; margin-left: 40px">
        {{ $t('2.清除过程需要验证钥匙卡密码') }}
      </div>
      <div style="color: orange; line-height: 41px; margin-bottom: 10px; margin-left: 40px">
        {{ $t('3.清除的数据包括系统中的所有账目和记录') }}
      </div>
      <div style="position: relative; padding-bottom: 20px" v-if="percent">
        <a-progress :percent="percent" :show-info="false" :strokeWidth="18" />
        <div
          style="position: absolute; z-index: 1; top: 20px; color: red; font-weight: 700; font-size: 18px"
          :style="{ left: percent + '%', 'margin-left': percent >= 5 ? '-40px' : '0' }"
        >
          {{ percent }}%
        </div>
      </div>
      <div style="display: flex; padding: 14px 0; line-height: 40px">
        <a-checkbox style="font-weight: bold; color: #000" v-model="autoFlushData.ivalue">{{
          $t('系统自动清理')
          }}</a-checkbox>
        <span style="margin-left: 10px">{{ $t('保留天数') }}：</span>
        <a-input-number
          v-model="autoFlushData.svalue"
          style="width: 80px; margin-left: 5px"
          :disabled="!autoFlushData.ivalue"
          :min="0"
        />
        <span style="margin-left: 10px">{{ $t('天') }}</span>
        <a-button type="primary"
                  v-enable-if="'BisSysParameterController:edit'"
          style="margin-left: 20px"
          @click="parameterChange('autoFlushData')"
          >{{ $t('保存') }}</a-button
        >
      </div>
      <div style="color: orange; line-height: 41px; margin-bottom: 10px">
        {{ $t('说明：启用系统自动清理功能后，系统将定时每15分钟自动清除保留天数之前的历史账目和记录数据。') }}
      </div>
      <!-- <div style="padding: 14px 0; line-height: 40px">
        <div style="margin-bottom: 10px">
          <span style="font-weight: bold; color: #000">{{ $t('账户恢复') }}</span>
        </div>
        <div style="margin-left: 20px; margin-bottom: 10px">
          <a-input-group compact>
            <span>{{ $t('选择文件') }}</span>
            <a-input style="width: 16%; margin-left: 10px" v-model="fileName" disabled></a-input>
            <a-upload
              name="file"
              :showUploadList="false"
              :multiple="false"
              :headers="tokenHeader"
              :before-upload="beforeUpload"
              accept=".xls"
            >
              <a-button style="color: white; background-color: #2eabff">
                {{ $t('浏览') }}
              </a-button>
            </a-upload>
          </a-input-group>
        </div>
        <div style="margin-left: 20px">
          <a-button style="color: white; background-color: #2eabff; margin-left: 20px" @click="handleImport">{{
            $t('恢复')
          }}</a-button>
        </div>
      </div> -->
      <DataManageModal ref="modalForm" @clearData="clearData"></DataManageModal>
    </a-spin>
  </a-card>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction, deleteAction, httpAction, postActionTimeout } from '@/api/manage'
import DataManageModal from './modules/DataManageModal'


let i
export default {
  name: 'DataManage',
  mixins: [JeecgListMixin],
  components: {
    DataManageModal,
  },
  data() {
    return {
      uploading: false,
      description: '数据管理',
      percent: 0,
      totalNum: 0,
      updateNum: 0,
      failNum: 0,
      list: [],
      pageNo: 1,
      pageSize: 999,
      clearManageLog:{
        name: 'clearManageLog',
        ivalue: 0,
        svalue: '',
        comment: '清除管理日志'
      },
      autoFlushData: {
        name: 'autoFlushData',
        ivalue: 0,
        svalue: '365',
        type: '',
        comment: '数据保留天数'
      },
      dataDisplayRatio: {
        name: 'dataDisplayRatio',
        ivalue: 0,
        svalue: '',
        comment: '数值显示比例',
      },
      recordDisplayNum: {
        name: 'recordDisplayNum',
        ivalue: 0,
        svalue: '',
        comment: '记录显示条数',
      },
      fileName: '',
      url: {
        list:'/member/bisMemberInfo',
        importExcelUrl: '/member/bisMemberInfo/offlineImportExcel',
      },
      file: {},
    }
  },
  computed: {
    tokenHeader() {
      let head = { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) }
      let tenantid = Vue.ls.get(TENANT_ID)
      if (tenantid) {
        head['tenant-id'] = tenantid
      }
      return head
    },
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  created() {
    this.getParameter('clearManageLog')
    this.getParameter('autoFlushData')
    this.getParameter('dataDisplayRatio')
    this.getParameter('recordDisplayNum')
  },
  methods: {
    beforeUpload(file) {
      this.file = file
      this.fileName = file.name
      return false
    },
    displaySet() {
      if (
        (this.dataDisplayRatio.ivalue === true || this.dataDisplayRatio.ivalue === 1) &&
        (this.dataDisplayRatio.svalue == undefined || this.dataDisplayRatio.svalue == '')
      ) {
        this.$message.warning(this.$t('数值显示比例未设置'))
        return
      }
      if (
        (this.recordDisplayNum.ivalue === true || this.recordDisplayNum.ivalue === 1) &&
        (this.recordDisplayNum.svalue == undefined || this.recordDisplayNum.svalue == '')
      ) {
        this.$message.warning(this.$t('记录显示条数未设置'))
        return
      }
      this.parameterChange('dataDisplayRatio')
      this.parameterChange('recordDisplayNum')
    },
    verifyKeyCard() {
      this.$refs.modalForm.visible = true
    },
    clearData() {
      let that = this
      i = 0
      let query = {
        pageNo: that.pageNo,
        pageSize: that.pageSize,
      }
      getAction('/system/bisTruncateTable/list', query).then((res) => {
        if (res.success) {
          that.list = res.result.records
          that.totalNum = res.result.total
          that.clearDataing(i)
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    clearDataing(x) {
      let that = this
      let query = {
        tableName: that.list[x].tableName,
      }
      deleteAction('/system/bisTruncateTable/truncateData', query).then((res) => {
        if (res.success) {
          that.updateNum += 1
        } else {
          that.failNum += 1
          that.$message.error(res.message)
        }
        i += 1
        that.percent = Number((((that.updateNum + that.failNum) / that.totalNum / 100.0) * 10000).toFixed(2))
        if (i < that.totalNum) {
          that.clearDataing(i)
        }
        if (that.updateNum + that.failNum == that.totalNum) {
          that.$message.success(that.$t('数据清除成功'))
          that.percent = 0
        }
      })
    },
    getParameter(name) {
      getAction('/bis/bisSysParameter/list', { name: name }).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            if (name === 'clearManageLog') {
              this.clearManageLog = res.result.records[0]
            }
            if (name === 'autoFlushData') {
              this.autoFlushData = res.result.records[0]
            }
            if (name === 'dataDisplayRatio') {
              this.dataDisplayRatio = res.result.records[0]
            }
            if (name === 'recordDisplayNum') {
              this.recordDisplayNum = res.result.records[0]
            }
          } else {
            if (name === 'autoFlushData') {
              this.autoFlushData.ivalue = 0
              this.autoFlushData.svalue = '365'
            }
          }
        }
      })
    },
    parameterChange(name) {
      let querydata = {}
      let url = ''
      let method = ''
      if (
        (name === 'autoFlushData' && this.autoFlushData.id) ||
        (name === 'dataDisplayRatio' && this.dataDisplayRatio.id) ||
        (name === 'recordDisplayNum' && this.recordDisplayNum.id) ||
        (name === 'clearManageLog' && this.clearManageLog.id)
      ) {
        url = '/bis/bisSysParameter/edit'
        method = 'put'
      } else {
        url = '/bis/bisSysParameter/add'
        method = 'post'
      }
      if (name === 'clearManageLog') {
        if (this.clearManageLog.ivalue === true || this.clearManageLog.ivalue === 1) {
          this.clearManageLog.ivalue = 1
        } else {
          this.clearManageLog.ivalue = 0
        }
        querydata = Object.assign({}, this.clearManageLog)
      }
      if (name === 'autoFlushData') {
        if (this.autoFlushData.ivalue === true || this.autoFlushData.ivalue === 1) {
          this.autoFlushData.ivalue = 1
        } else {
          this.autoFlushData.ivalue = 0
        }
        querydata = Object.assign({}, this.autoFlushData)
      }
      if (name === 'dataDisplayRatio') {
        if (this.dataDisplayRatio.ivalue === true || this.dataDisplayRatio.ivalue === 1) {
          this.dataDisplayRatio.ivalue = 1
        } else {
          this.dataDisplayRatio.ivalue = 0
        }
        querydata = Object.assign({}, this.dataDisplayRatio)
      }
      if (name === 'recordDisplayNum') {
        if (this.recordDisplayNum.ivalue === true || this.recordDisplayNum.ivalue === 1) {
          this.recordDisplayNum.ivalue = 1
        } else {
          this.recordDisplayNum.ivalue = 0
        }
        querydata = Object.assign({}, this.recordDisplayNum)
      }
      httpAction(url, querydata, method).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          if (name === 'clearManageLog') {
            this.getParameter('clearManageLog')
          }
          if (name === 'autoFlushData') {
            this.getParameter('autoFlushData')
          }
          if (name === 'dataDisplayRatio') {
            this.getParameter('dataDisplayRatio')
          }
          if (name === 'recordDisplayNum') {
            this.getParameter('recordDisplayNum')
          }
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleImport() {
      let that=this
      if(!that.fileName){
        that.$message.warning(this.$t('请选择文件'))
        return
      }
      const formData = new FormData()
      formData.append('files[]', that.file)
      that.uploading = true
      postActionTimeout(that.url.importExcelUrl, formData, 24*60*60*1000).then(res => {
        if (res.success) {
          that.$message.success(res.message)
          that.visible = false
        } else {
          that.$message.warning(res.message)
        }
      }).finally(()=>{
        that.uploading = false
      })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>